import {useNavigate, useParams} from "react-router-dom";
import {
    Box,
    Button,
    ButtonGroup,
    Drawer,
    DrawerBody,
    DrawerCloseButton,
    DrawerContent, DrawerFooter,
    DrawerHeader,
    DrawerOverlay,
    FormLabel,
    Input,
    Popover,
    PopoverArrow,
    PopoverBody,
    PopoverCloseButton,
    PopoverContent,
    PopoverFooter,
    PopoverHeader,
    PopoverTrigger, Select,
    Stack, Text,
    useColorModeValue,
    useDisclosure,
    useToast
} from "@chakra-ui/react";
import {useAuth} from "../../hooks/index.js";
import React, {useEffect, useState} from "react";
import {
    delMedicine,
    findByName,
    getAllCategory,
    getAllMedicine,
    getAllMedicinePage,
    getMedicineCount, saveMedicine
} from "../../api/medicine.js";
import {handleResult, handleResultNoRoute} from "../../api/result.js";
import ManageSearchBar from "../../components/ManageSearchBar.jsx";
import {AddIcon, DeleteIcon, EditIcon} from "@chakra-ui/icons";
import {DoctorShowSearchBar} from "../../components/DoctorShowSearchBar.jsx";
import {addMedicine2List} from "../../api/medicineList.js";

// 药品列表, 添加到药单
export function DoctorMedicineAddPage() {
    const {id: orderId} = useParams()

    const navigator = useNavigate()
    const toast = useToast()
    const {authInfo} = useAuth()

    // 数据获取
    const [medicines, setMedicines] = useState([])
    const [total, setTotal] = useState([])
    useEffect(() => {
        console.log(authInfo)
        // 请求数据
        // getAllMedicine().then((data) => {
        getAllMedicinePage({page: 0, size: 6}).then((data) => {
            setMedicines(data.data)
        })
        getMedicineCount().then(r => setTotal(r.data))
    }, []);

    // ManageSearchBar states
    const [value, setValue] = useState('')
    let timer = new Date()
    const [startDate, setStartDate] = useState(timer.toLocaleDateString())
    const [endDate, setEndDate] = useState(timer.toLocaleDateString())

    let searchItem = {
        placeholder: '药品名称',
        value,
        onChange: (e) => {
            setValue(e.target.value)
        },
        onClick: (e) => {
            if (value === '') {
                getAllMedicine().then(r => {
                    handleResultNoRoute(r, toast, '', '查询成功')
                    setMedicines(r.data)
                })
                return
            }
            findByName(value).then(r => {
                handleResultNoRoute(r, toast, '', '查询成功')
                setMedicines(r.data)
            })
        }
    }
    let dateSearchItem = {
        onChange: (date, dateString) => {
            console.log(date, dateString)
            setStartDate(dateString[0])
            setEndDate(dateString[1])
        },
        onClick: (e) => {
            console.log(startDate, endDate)
        }
    }
    // 当前页码
    const [curIdx, setCurIdx] = useState(0);
    let pageSearchItem = {
        total: (Math.floor(total / 6) + 1), curIdx,
        onChange: (e) => {
            setCurIdx(e.target.value)
        },
        onLeftClick: () => {
            console.log(curIdx)
            if (curIdx > 1) {
                setCurIdx((curIdx - 1))
                return
            }
            toast({
                title: `已到达第一页!`,
                status: 'warning',
                position: 'top',
                isClosable: true,
            })
        },
        onRightClick: () => {
            if (curIdx < (Math.floor(total / 6) + 1)) {
                setCurIdx((curIdx + 1))
                return
            }
            toast({
                title: `已到达最后一页!`,
                status: 'warning',
                position: 'top',
                isClosable: true,
            })
        },
        onClick: () => {
            console.log(curIdx)
            getAllMedicinePage({page: curIdx, size: 6})
                .then(r => {
                    handleResultNoRoute(r, toast, '', '查询成功')
                    setMedicines(r.data)
                })
        }
    }

    // 添加按钮 弹出drawer
    const {isOpen, onOpen, onClose} = useDisclosure()
    // 用于弹出时聚焦
    const firstField = React.useRef()

    // drawer里的表单的数据
    const [mid, setMid] = useState(0) // 药品id
    const [name, setName] = useState('') // 药品名称
    const [number, setNumber] = useState(0) // 药品数量

    // 操作栏
    function onAddClick(id, name) {
        console.log(id)
        setMid(id)
        setName(name)
        onOpen()
    }

    return (
        <Stack
            align={'start'}
            justify={'start'}
            spacing={4}
            mb={6}
            className={useColorModeValue('', 'dark')}>
            <DoctorShowSearchBar
                pageSearchItem={pageSearchItem}
                searchItem={searchItem}
                dateSearchItem={dateSearchItem}/>
            <div className={"table-container "}>
                <table className="table table-hover">
                    <thead>
                    <tr>
                        <th>药品名称</th>
                        <th>药品分类</th>
                        <th>药品库存</th>
                        <th>药品单价</th>
                        <th>操作</th>
                    </tr>
                    </thead>
                    <tbody>
                    {
                        medicines.map((item) => (
                            <tr key={item.id}>
                                <td>{item.name}</td>
                                <td>{item.category}</td>
                                <td>{item.number}</td>
                                <td>{item.price}</td>
                                <td>
                                    <Stack direction='row' spacing={4}>
                                        <Button
                                            onClick={() => onAddClick(item.id, item.name)}
                                            leftIcon={<AddIcon/>} size='sm'
                                            colorScheme='teal' variant='solid'>
                                            添加
                                        </Button>
                                    </Stack>
                                </td>
                            </tr>
                        ))
                    }
                    </tbody>
                </table>
            </div>
            <Drawer
                size={'md'}
                isOpen={isOpen}
                placement='right'
                initialFocusRef={firstField}
                onClose={onClose}
            >
                <DrawerOverlay/>
                <DrawerContent>
                    <DrawerCloseButton/>
                    <DrawerHeader borderBottomWidth='1px'>
                        添加药品到药单
                    </DrawerHeader>

                    <DrawerBody>
                        <Stack spacing='24px'>
                            <Box>
                                <Text>{name}</Text>
                            </Box>
                            <Box>
                                <FormLabel htmlFor='category'>药品数量</FormLabel>
                                <Input
                                    onChange={(e) => setNumber(e.target.value)}
                                    value={number} type="number"/>
                            </Box>
                        </Stack>
                    </DrawerBody>

                    <DrawerFooter borderTopWidth='1px'>
                        <Button variant='outline' mr={3} onClick={onClose}>
                            取消
                        </Button>
                        <Button onClick={() => {
                            console.log(name, number)
                            // saveMedicine({name, categoryId}).then(r =>
                            //     handleResult(r, toast, null, '添加成功')
                            // )
                            addMedicine2List({mid, oid: orderId, number})
                                .then(r => handleResultNoRoute(r, toast, null, '添加成功'))
                        }} colorScheme='blue'>提交</Button>
                    </DrawerFooter>
                </DrawerContent>
            </Drawer>
        </Stack>
    )
}